//
//  HTableView.swift
//  NetWork
//
//  Created by Delin Meng 孟德林 on 2018/9/21.
//  Copyright © 2018年 Delin Meng 孟德林. All rights reserved.
//

import UIKit

public class XCTableViewRow  {
    var sectionName : String
    var identifier : String
    var data:Any
    var rowHeight :CGFloat
    var nibName : String


    /// 用来构建TableView将要显示的Cell类型
    ///
    /// - Parameters:
    ///   - sectionName: 用来统计几个section,如果Name相同,则在同一个section中
    ///   - identifier: cell的identifier
    ///   - data: cell 将要用到的数据
    ///   - rowHeight: cell的初始高度
    ///   - nibName: cell的xib名字,如果为空,默认为等于identifier
    init(identifier:String,nibName:String,sectionName:String,rowHeight:CGFloat,data:Any) {
        self.identifier = identifier
        self.nibName = nibName
        self.sectionName = sectionName
        self.rowHeight = rowHeight
        self.data = data
    }
}


public class HTableView: UITableView {


    public var sections : [[XCTableViewRow]] = []

    private var registerIdentifier:[String] = []

    public var sectionCount:Int{
        return sections.count
    }

    public func heightForRowAt(indexPath: IndexPath) -> CGFloat{
        let r = sections[indexPath.section][indexPath.row]
        return r.rowHeight
    }

    func setup(rows:[XCTableViewRow],bundle:Bundle?){
        sections = []
        var sectionNames:[String] = []
        for row in rows{
            //防止重复注册
            if !registerIdentifier.contains(row.identifier){
                self.register(UINib.init(nibName: row.nibName, bundle: bundle), forCellReuseIdentifier: row.identifier)
                registerIdentifier.append(row.identifier)
            }

            //区分section
            if !sectionNames.contains(row.sectionName){
                sectionNames.append(row.sectionName)
                sections.append([XCTableViewRow]())
            }

            //给section中添加row
            if let index = sectionNames.index(of: row.sectionName){
                sections[index].append(row)
            }
        }
        reloadData()

    }
}
